<?php

// 公共函数库

/**
 * 解密已经加密了的cookie
 *
 * @param string $encryptedText
 * @return string
 */
function _decrypt($encryptedText)
{
    $key = C('secret_key');
    $cryptText = base64_decode($encryptedText);
    $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
    $decryptText = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $cryptText, MCRYPT_MODE_ECB, $iv);
    return trim($decryptText);
}

/**
 * 加密cookie
 *
 * @param string $plainText
 * @return string
 */
function _encrypt($plainText)
{
    $key = C('secret_key');
    $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
    $encryptText = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $plainText, MCRYPT_MODE_ECB, $iv);
    return trim(base64_encode($encryptText));
}

/**
 *生成几位数的数据
 */
function getRandNum($num){
      $arr = range(0,$num);
      shuffle($arr);
      $str = implode('',$arr);
      return $str;
}

/**
 * 浏览器友好的变量输出
 * @param mixed $var 变量
 * @param boolean $echo 是否输出 默认为True 如果为false 则返回输出字符串
 * @param string $label 标签 默认为空
 * @param boolean $strict 是否严谨 默认为true
 * @return void|string
 */
function dd($var, $echo = true, $label = null, $strict = true)
{
    $label = ($label === null) ? '' : rtrim($label) . ' ';
    if (!$strict) {
        if (ini_get('html_errors')) {
            $output = print_r($var, true);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        } else {
            $output = $label . print_r($var, true);
        }
    } else {
        ob_start();
        var_dump($var);
        $output = ob_get_clean();
        if (!extension_loaded('xdebug')) {
            $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        }
    }
//	if ($echo) {
//		echo($output);
//		return null;
//	} else
//		return $output;

    echo($output);
    exit;
}

/**
 * 字符串截取，支持中文和其他编码
 * static
 * access public
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 * return string
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
    if(function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif(function_exists('iconv_substr')) {
        $slice = iconv_substr($str,$start,$length,$charset);
        if(false === $slice) {
            $slice = '';
        }
    }else{
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }
    return $suffix ? $slice.'...' : $slice;
}

/**
 * curl 函数
 * @param string $url 请求的地址
 * @param string $type POST/GET/post/get
 * @param array $data 要传输的数据
 * @param string $err_msg 可选的错误信息（引用传递）
 * @param int $timeout 超时时间
 * @param array 证书信息
 * @author 勾国印
 */
function GoCurl($url, $type, $data = false, &$err_msg = null, $timeout = 20, $cert_info = array())
{
    $type = strtoupper($type);
    if ($type == 'GET' && is_array($data)) {
        $data = http_build_query($data);
    }
    $option = array();

    if ( $type == 'POST' ) {
        $option[CURLOPT_POST] = 1;
    }
    if ($data) {
        if ($type == 'POST') {
            $option[CURLOPT_POSTFIELDS] = $data;
        } elseif ($type == 'GET') {
            $url = strpos($url, '?') !== false ? $url.'&'.$data :  $url.'?'.$data;
        }
    }

    $option[CURLOPT_URL]            = $url;
    $option[CURLOPT_FOLLOWLOCATION] = TRUE;
    $option[CURLOPT_MAXREDIRS]      = 4;
    $option[CURLOPT_RETURNTRANSFER] = TRUE;
    $option[CURLOPT_TIMEOUT]        = $timeout;

    //设置证书信息
    if(!empty($cert_info) && !empty($cert_info['cert_file'])) {
        $option[CURLOPT_SSLCERT]       = $cert_info['cert_file'];
        $option[CURLOPT_SSLCERTPASSWD] = $cert_info['cert_pass'];
        $option[CURLOPT_SSLCERTTYPE]   = $cert_info['cert_type'];
    }

    //设置CA
    if(!empty($cert_info['ca_file'])) {
        // 对认证证书来源的检查，0表示阻止对证书的合法性的检查。1需要设置CURLOPT_CAINFO
        $option[CURLOPT_SSL_VERIFYPEER] = 1;
        $option[CURLOPT_CAINFO] = $cert_info['ca_file'];
    } else {
        // 对认证证书来源的检查，0表示阻止对证书的合法性的检查。1需要设置CURLOPT_CAINFO
        $option[CURLOPT_SSL_VERIFYPEER] = 0;
    }

    $ch = curl_init();
    curl_setopt_array($ch, $option);
    $response = curl_exec($ch);
    $curl_no  = curl_errno($ch);
    $curl_err = curl_error($ch);
    curl_close($ch);
    // error_log
    if($curl_no > 0) {
        if($err_msg !== null) {
            $err_msg = '('.$curl_no.')'.$curl_err;
        }
    }
    return $response;
}

/**
 * 时间格式化函数
 * @param  [type] $time 需要格式化的字符串
 * @return [string]     返回格式化后的字符串
 */
function dateFormat($time){
    $Now = time();
    $diff = $Now-$time;
    $str = '';
    switch ($diff) {
        case $diff<60;
            $str = $diff."秒前";
            break;
        case $diff>60&&$diff<3600;
            $str = floor($diff/60).'分钟前';
            break;
        case $diff>3600&&$diff<3600*24;
            $str = floor($diff/3600)."小时前";
            break;
        case $diff>3600*24&&$diff<3600*24*7;
            $str = floor($diff/(3600*24)).'天前';
            break;
        case $diff>3600*24*7&&$diff<3600*24*30;
            $str = floor($diff/(3600*24*7)).'星期前';
            break;
        case $diff>3600*24*30&&$diff<3600*24*30*12;
            $str = floor($diff/(3600*24*30))."月前";
            break;
        default;
            $str = date("Y-m-d H:m:d",$time);
            break;
    }
    return $str;
}

/**
 * 中文分词处理方法
 *+---------------------------------
 * @param stirng  $string 要处理的字符串
 * @param boolers $sort=false 根据value进行倒序
 * @param Numbers $top=0 返回指定数量，默认返回全部
 *+---------------------------------
 * @return void
 */
function scws($word) {
     $url = 'http://www.xunsearch.com/scws/demo/v48.php';
     $data = "mydata=".$word;
     $res = GoCurl($url,'POST',$data);
     $regex4="/<textarea cols=60 .*?>.*?<\/textarea>/ism";
     if(preg_match_all($regex4, $res, $matches)){
          foreach($matches[0] as $v){
                $v = htmlentities($v);
                $allword = substr($v,strpos($v,'&quot;&gt;')+strlen('&quot;&gt;'));
                $allword = substr($allword,0,strpos($allword,'&lt;'));
          }
          // 通过空格 分词
          $spiltword = explode(" ",$allword);
          $filler = array(',','。','.',')','(','-',':','、','，',"《",'》');
          // 过滤符号标点 / 单字符
          foreach($spiltword as $k => $v){
                if(in_array($v,$filler)){
                     unset($spiltword[$k]);
                }
                $str = strlen($v);
                if($str==3){
                      unset($spiltword[$k]);
                }
          }
          // 数组去重
          $spiltword = array_unique($spiltword);
          return $spiltword;
     }
}